<template>
  <view class="components-form">
    
    <!-- 顶部自定义导航 -->
    <tn-nav-bar fixed>贷款申请</tn-nav-bar>
    
    <!-- 页面内容 -->
    <view :style="{paddingTop: vuex_custom_bar_height + 'px'}">
      
      <dynamic-demo-template :full="true" :fullWindowsScroll="true" @click="click">
        <tn-form :model="model" ref="form" errorType="message" labelPosition="top" labelAlign="left">
		  <view v-show="step==1">
			  <tn-form-item label="抵押货物" prop="amountId" leftIcon="identity" :required="true" labelPosition="top" labelAlign="left">
			    <tn-input v-model="goodsName" type="text" placeholder="请选择抵押货物" :border="false" :selectOpen="selectShow" @click="selectShow = true"></tn-input>
			  </tn-form-item>
			  <tn-form-item label="贷款期限(月)" prop="loanMonth" leftIcon="identity" :required="true" labelPosition="top" labelAlign="left">
			    <tn-input v-model="loanMonthLabel" type="text" placeholder="请输入月数" :border="false" :selectOpen="selectShow1" @click="selectShow1 = true"></tn-input>
		
			  </tn-form-item>
			  <tn-form-item label="贷款日利率(单利)" prop="dailyRate" leftIcon="identity" :required="true" labelPosition="top" labelAlign="left">
			    <tn-input disabled v-model="model.dailyRate" type="text" placeholder="请输入利率" :border="false" ></tn-input>
			  	<view slot="right"> <text class="tn-color-brown tn-padding-right-xs">%</text></view>
			  </tn-form-item>
		  	 <tn-form-item label="贷款金额" prop="loanAmount" leftIcon="identity" :required="true" labelPosition="top" labelAlign="left">
		  	   <tn-input disabled v-model="model.loanAmount" type="text" placeholder="选择抵押货物后自动生成" :border="false"></tn-input>
		  	 </tn-form-item>
		  </view>
         <view v-show="step==2">
         	 <tn-form-item label="贷款人" prop="loanPerson" leftIcon="identity" :required="true" labelPosition="top" labelAlign="left">
         	   <tn-input disabled v-model="model.loanPerson" type="text" placeholder="请输入贷款人" :border="false"></tn-input>
         	 </tn-form-item>
         	 <tn-form-item label="身份证号" prop="idCard" leftIcon="identity" :required="true" labelPosition="top" labelAlign="left">
         	   <tn-input disabled v-model="model.idCard" type="text" placeholder="请输入身份证号" :border="false"></tn-input>
         	 </tn-form-item>
         	 <tn-form-item label="手机号码" prop="phone" rightIcon="phone" :required="true" labelPosition="top" labelAlign="left">
         	   <tn-input disabled v-model="model.phone" type="number" placeholder="请输入手机号码" :border="false"></tn-input>
         	 </tn-form-item>
			 <tn-form-item label="还款方式" prop="repayMethod" :required="true" labelPosition="top" labelAlign="left">
			   <tn-input v-model="repayMethodLabel" type="text" placeholder="请选择还款方式" :border="false" :selectOpen="selectShow2" @click="selectShow2 = true"></tn-input>
			 </tn-form-item>
			 <tn-form-item label="收还款银行账号" prop="bankCard" leftIcon="identity" :required="true" labelPosition="top" labelAlign="left">
			   <tn-input v-model="model.bankCard" type="text" placeholder="银行卡号" :border="false"></tn-input>
			 </tn-form-item>
         </view>
		 <view v-show="step==3">
			 <tn-form-item label="贷款金额"  labelPosition="left" labelWidth="200" labelAlign="left">
			   <tn-input disabled v-model="model.loanAmount" type="text"  :border="false"></tn-input>
			 </tn-form-item>
			 <tn-form-item label="贷款期限(月)"  labelPosition="left" labelWidth="200" labelAlign="left">
			   <tn-input disabled v-model="loanMonthLabel" type="text"  :border="false" :selectOpen="selectShow1" @click="selectShow1 = true"></tn-input>
			 </tn-form-item>
			 <tn-form-item label="日利率(单利)" labelPosition="left" labelWidth="200" labelAlign="left">
			   <tn-input disabled v-model="model.dailyRate" type="text"  :border="false" ></tn-input>
			   <view slot="right"> <text class="tn-color-brown tn-padding-right-xs">%</text></view>
			 </tn-form-item>
			 <tn-form-item label="银行账号" labelWidth="200" labelPosition="left" labelAlign="left">
			   <tn-input v-model="model.bankCard" type="text" disabled :border="false"></tn-input>
			 </tn-form-item>
			 <tn-form-item label="还款方式" labelPosition="left" labelWidth="200" labelAlign="left">
			   <tn-input disabled v-model="repayMethodLabel" type="text"  :border="false" ></tn-input>
			 </tn-form-item>
			 <tn-form-item label="还款计划"  labelPosition="top" labelAlign="left">
			     <view class="tn-flex tn-flex-wrap tn-padding-bottom">
			       <view class="king-list tn-margin-top-sm">
			         <view class="king-icon">
			           <text class='tn-text-lg tn-margin-left tn-color-black'>还款总额¥{{totalRepay}},</text>
			     	   <text class='tn-text-lg tn-margin-left tn-color-orange'>利息总额¥{{totalInterest}}</text>
			         </view>
					 <view class='king-item  tn-icon-circle-fill tn-color-grey' v-for="item in plan">
					   <view class="resume text-lg">
					 	 <text>{{item.repay_date}}</text>
					   </view>
					    <view class="tn-flex">
					      <view class="tn-margin-sm tn-padding-top-sm" style="width: 100%;">
					        <view class="tn-flex-wrap" >
					          <text class="tn-text-xl tn-text-bold tn-color-black clamp-text-2 tn-text-justify">
					            ¥{{item.money_interest}}
					          </text>
							  <text class="tn-text-df tn-color-gray clamp-text-2 tn-text-justify">
								本金：{{item.money}} 利息：{{item.interest}}
							  </text>
					        </view>
					      </view>
					    </view>
					 </view>
			       </view>
			           
			     </view>
			 </tn-form-item>
		 </view>
        </tn-form>
        <view class="agreement" v-show="step==3">
          <tn-checkbox v-model="agreement" @change="agreementCheckChange"></tn-checkbox>
          <view class="agreement-text">本人已阅读同意签署<text class="tn-color-blue" @click="tn('/pages/loan/contract')"><<货物抵押借款合同>></text></view>
        </view>
		<tn-button v-show="step>1 && step<=3" backgroundColor="#01BEFF" fontColor="#FFFFFF" width="100%" @click="before">上一步</tn-button>
		<view class="tn-margin-top-sm">
			
		</view>
		<tn-button v-show="step<3" backgroundColor="#01BEFF" fontColor="#FFFFFF" width="100%" @click="next">下一步</tn-button>
        <tn-button v-show="step==3" backgroundColor="#01BEFF" fontColor="#FFFFFF" width="100%" @click="submit">提交</tn-button>
      </dynamic-demo-template>

      <!-- 货物select -->
      <tn-select
        v-model="selectShow"
        mode="single"
        :list="goodsList"
        @confirm="goodsSelectConfirm"
      ></tn-select>
	  <!-- 贷款月数select -->
	  <tn-select
	    v-model="selectShow1"
	    mode="single"
	    :list="monthsList"
	    @confirm="mounthSelectConfirm"
	  ></tn-select>
	  <!-- 还款方式select -->
	  <tn-select
	    v-model="selectShow2"
	    mode="single"
	    :list="typesList"
	    @confirm="typeSelectConfirm"
	  ></tn-select>
      
    </view>
    
  </view>
</template>

<script>
  import dynamicDemoTemplate from '@/libs/components/dynamic-demo-template.vue'
  import templatePageMixin from '@/libs/mixin/template_page_mixin.js'
  import {loanGoods,applyLoan} from '@/api/loan.js'
  import {getPersonInfo} from '@/api/auth.js'
  import dayjs from '@/util/dayjs.min.js'
  import Decimal from '@/util/decimal.js';
  export default {
    name: 'componentsForm',
	mixins: [templatePageMixin],
    components: {dynamicDemoTemplate},
    data() {
      return {
		goodsList:[],
		plan:[],
		totalRepay:0,
		totalInterest:0,
		loanMonthLabel:'',
		repayMethodLabel:'',
		btnTitle:"下一步",
		step:1,
        selectShow: false,
		selectShow1: false,
		selectShow2: false,
        typesList:[
          {
            label: '按月付息，到期还本',
            value: 'month_interest'
          },
          {
            label: '等额本息',
            value: 'equal_interest'
          },
        ],
		monthsList: [
		  {
		    label: '6个月',
		    value: 6
		  },
		  {
		    label: '12个月',
		    value: 12
		  }
		],
		agreement: false,
        model: {
          amountId: null,
          loanAmount: '',
          loanMonth: '',
          dailyRate: '0.07',
          loanPerson: '',
          idCard: '',
          phone: '',
          repayMethod: '',
          bankCard: '',
          loanStart: '',
          loanEnd: '',
        },
        rules: {
          loanAmount: [
            {
              required: true,
              message: '请输入贷款金额',
              trigger: ['change','blur'],
            }
          ],
          amountId: [
          	{
          		required: true,
          		message: '请选择抵押货物',
          		trigger: ['change','blur'],
          	}
          ],
          phone: [
          	{
          		required: true,
          		message: '请输入手机号码',
          		trigger: ['change','blur'],
          	}
          ],
          loanMonth: [
            {
              required: true,
              message: '请选择贷款期限',
              trigger: ['change','blur'],
            }
          ],
          dailyRate: [
            {
              required: true,
              message: '请选择日利率',
              trigger: ['change','blur']
            }
          ],
          loanPerson: [
            {
              required: true,
              message: '请输入贷款人',
              trigger: ['change','blur']
            }
          ],
          idCard: [
            {
              required: true,
              message: '请输入身份证号码',
              trigger: ['change','blur']
            }
          ],
          repayMethod: [
            {
              required: true,
              message: '请选择还款方式',
              trigger: ['change','blur']
            }
          ],
          bankCard: [
            {
              required: true,
              message: '请输入银行卡号码',
              trigger: ['change','blur']
            },
			{
				// 此为同步验证，可以直接返回true或者false，如果是异步验证，稍微不同，见下方说明
				validator: (rule, value, callback) => {
					return this.$t.test.bankCard(value);
				},
				message: '卡号格式错误',
				trigger: ['change','blur'],
			},
          ],
        }
      }
    },
	mounted() {
		this.$refs.form.setRules(this.rules)
	},
	created(){
		this.initGoods()
		this.personInfo()
	},
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      click(event) {
        this[event.methods] && this[event.methods](event)
      },
	  personInfo(){
	   getPersonInfo().then(res=>{
	  		 if(res){
	  			 this.model.loanPerson=res.accountName
				 this.model.idCard=res.idCard
				 this.model.phone=this.$store.state.vuex_user.user.phone
	  		 }
	   }).catch(err=>{
	  		this.$t.message.toast(err.data.message)	 			 
	   })
	  },
	  initGoods(){
		  loanGoods().then(res=>{
			  res.forEach(it=>{
				  this.goodsList.push({label:it.goodsName+'-'+it.goodsNo,value:it.id, extra:it.amount})
			  })
		  })
	  },
	  before(){
		this.step=this.step-1
	  },
	  next(){
		  let validate = true
		  this.$refs.form.validate(valid => {
			  if(this.step==1){
				  this.$refs.form.fields.forEach(file=>{
					  if(file.prop=='amountId' &&file.validateState=='error'){
							validate=false		  
					  }
					  if(file.prop=='loanMonth' &&file.validateState=='error'){
					  		validate=false		  
					  }
					  if(file.prop=='dailyRate' &&file.validateState=='error'){
					  		validate=false		  
					  }
					  if(file.prop=='loanAmount' &&file.validateState=='error'){
					  		validate=false		  
					  }
				  })
			  }
			  if(this.step==2){
				  this.$refs.form.fields.forEach(file=>{
					  if(file.prop=='loanPerson' &&file.validateState=='error'){
							validate=false		  
					  }
					  if(file.prop=='idCard' &&file.validateState=='error'){
							validate=false		  
					  }
					  if(file.prop=='phone' &&file.validateState=='error'){
							validate=false		  
					  }
					  if(file.prop=='repayMethod' &&file.validateState=='error'){
							validate=false		  
					  }
					  if(file.prop=='bankCard' &&file.validateState=='error'){
							validate=false		  
					  }
				  })
			  }
		    if (validate) {
				this.step=this.step+1
				if(this.step==3){// 生成还款计划
					this.initPlan()
				}
		    } else {
		      // 验证失败
		    }
		  })
	  },
	  initPlan(){
		  this.plan = []
		  this.totalInterest =0 
		  this.totalRepay=0
		  const now = dayjs()
		  //固定每月18日还款，方便统计
		  const fix = dayjs().date(18)
		  let start = now.add(5, 'day') //5天审核以及财务打款时间
		  if(start.isBefore(fix)){ //确认当月18日放款
		  	start = fix
		  }else{//确认下月18日放款
		  	start = fix.add(1, 'month')
		  }
		  if(this.model.repayMethod=='month_interest'){
			  let m=0
			  let last_start = start
			  for(var i=1;i<=Number(this.model.loanMonth);i++){
				  const term_end = start.add(i, 'month')
				  const days = term_end.diff(last_start,'day')
				  const inter = Decimal.mul(this.model.loanAmount, this.model.dailyRate).div(100).mul(days).toFixed(2)
				  console.log(inter)
				  if(i==Number(this.model.loanMonth)){
					  m=this.model.loanAmount
				  }
				  const mi = Decimal.add(m,inter).toFixed(2)
				  console.log(mi)
				  this.plan.push({
					  'repay_date':term_end.format('YYYY-MM-DD'),
					  'money':m,
					  'interest':inter,
					  'money_interest':mi
				  }) 
				  this.totalInterest = Decimal.add(this.totalInterest, inter).toFixed(2)
				  last_start = term_end
			  }
			  this.totalRepay = Decimal.add(this.model.loanAmount,this.totalInterest).toFixed(2) 
		  }
          if(this.model.repayMethod=='equal_interest'){
			  console.log('-----------',this.model.repayMethod)
			  let last_start = start
			  // 计算每月固定还款额
			  // 月利率按30天计算
			  const monthRate = Decimal.div(this.model.dailyRate,100).mul(30)
			  const a = Decimal.mul(monthRate,Decimal.pow(Decimal.add(1,monthRate),this.model.loanMonth))
			  const b = Decimal.pow(Decimal.add(1,monthRate), this.model.loanMonth).sub(1);
			  let monthReapy = Decimal.div(a,b).mul(this.model.loanAmount).toFixed(2)
			  console.log('-----------',monthReapy)  
			  //累计还款本金
			  let total = 0
			  for(var i=1;i<=Number(this.model.loanMonth);i++){
				  const term_end = start.add(i, 'month')
				  const days = 30
				  const inter = Decimal.sub(this.model.loanAmount,total).mul(this.model.dailyRate).div(100).mul(days).toFixed(2)
				  console.log('-----inter------',inter)  
				  this.plan.push({
					  'repay_date':term_end.format('YYYY-MM-DD'),
					  'money':Decimal.sub(monthReapy,inter).toFixed(2),
					  'interest':inter,
					  'money_interest':monthReapy
				  }) 
				  total = Decimal.add(total,monthReapy).sub(inter)
				  this.totalInterest = Decimal.add(this.totalInterest,inter).toFixed(2)
				  last_start = term_end
			  }
			  this.totalRepay = Decimal.add(this.model.loanAmount,this.totalInterest)
		  }
          //设置贷款开始结束日期
		  this.model.loanStart=start.format('YYYY-MM-DD')
		  if(this.plan.length>0){
			  this.model.loanEnd=this.plan[this.plan.length-1]['repay_date']
		  }
	  },
      // 表单提交
      submit() {
        this.$refs.form.validate(valid => {
          if (valid) {
            // 验证通过
            if (!this.agreement) {
              this.$t.message.toast('请勾选协议')
              return
            }else{
				applyLoan(this.model).then(res=>{
					this.$t.message.toast('提交成功')
					this.tn('/pages/loan/loan_process')
				}).catch(err=>{
					this.$t.message.toast('提交失败')
				})
			}
          } else {
            // 验证失败
			this.$t.message.toast('请正确填写表单信息')
          }
        })
      },
	  // 点击还款方式选择器
	  typeSelectConfirm(event) {
        this.repayMethodLabel = `${event[0]['label']}`
		this.model.repayMethod = `${event[0]['value']}`
      },
	  // 点击月数选择器
	  mounthSelectConfirm(event) {
        this.loanMonthLabel = `${event[0]['label']}`
		this.model.loanMonth = `${event[0]['value']}`
      },
      // 点击货物列选择器
      goodsSelectConfirm(event) {
        this.goodsName = `${event[0]['label']}`
		this.model.amountId = `${event[0]['value']}`
		this.model.loanAmount = `${event[0]['extra']}`
      },
      // 同意协议状态修改
      agreementCheckChange() {
        this.agreement = !this.agreement
      },
	  // 跳转
	  tn(e) {
	  	uni.navigateTo({
	  		url: e,
	  	});
	  },
    }
  }
</script>

<style lang="scss" scoped>
  
  .agreement {
    display: flex;
    align-items: center;
    margin: 40rpx 0;
    
    &-text {
      padding-left: 8rpx;
      color: $tn-font-sub-color;
    }
  }
 /* 简历内容 */
 .king-list {
   display: block;
   // background-color: #ffffff;
 }
 
 .king-list .king-icon {
   width: 100%;
   text-align: left;
   padding: 20rpx 0 20rpx 37rpx;
   font-size: 26rpx;
   color: #888;
   display: block;
 }
 
 .king-list>.king-item {
   padding: 30rpx 30rpx 30rpx 120rpx;
   position: relative;
   display: block;
   z-index: 0;
 }
 
 .king-list>.king-item::after {
   content: "";
   display: block;
   position: absolute;
   width: 1rpx;
   background-color: #E6E6E6;
   left: 60rpx;
   height: 100%;
   top: 0;
   z-index: 8;
 }
 
 .king-list>.king-item::before {
   display: block;
   position: absolute;
   top: 36rpx;
   z-index: 9;
   background-color: #ffffff;
   width: 50rpx;
   height: 50rpx;
   text-align: center;
   border: none;
   line-height: 50rpx;
   left: 36rpx;
 } 
 
 .resume {
   display: flex;
   justify-content: space-between;
   padding-top: 10rpx;
   border-radius: 6rpx;
   color: #666;
   line-height: 1.6;
 }
 
 .resume+.resume {
   margin-top: 20rpx;
 }
 
 .resume2 {
   padding-top: 10rpx;
   border-radius: 6rpx;
   display: block;
   color: #666;
   line-height: 1.6;
   text-align: justify;
 }
 
 /* 文字截取*/
 .clamp-text-1 {
   -webkit-line-clamp: 1;
   display: -webkit-box;
   -webkit-box-orient: vertical;
   text-overflow: ellipsis;
   overflow: hidden;
 }
 
 .clamp-text-2 {
   -webkit-line-clamp: 2;
   display: -webkit-box;
   -webkit-box-orient: vertical;
   text-overflow: ellipsis;
   overflow: hidden;
 }
 
</style>
